/**
 * @file acpitemp.c
 * ACPI temperature source for TrayInfo.
 */

/* ACPI temperature support added by Laszlo Ashin <kodest@gmail.com> */

#include <stdio.h>
#include <stdlib.h>

#include "trayinfo.h"
#include "utils.h"

/** Source handle. */
static source_handle_t *acpitemp_sh;

#define READPERIOD	10

static int
acpitemp_read(void)
{
	int temp = 0;
	const char *idlist[] = { "temperature" };
	char *vallist[] = { NULL };

	collect_data_from_file(
		"/proc/acpi/thermal_zone/THRM/temperature",
		":", 1, idlist, vallist
	);
	if (*vallist) {
		if (sscanf(*vallist, "%d", &temp) != 1)
			temp = 0;

		free(*vallist);
	}
	return temp;
}

static int
acpitemp_write(double now, int fd)
{
	static double lasttime = 0.0f;
	static int temp = 0;

	if (now >= lasttime + READPERIOD) {
		temp = acpitemp_read();
		lasttime = now;
	}
	if (temp) {
		return show("%02dC", temp);
	}

	return 0;
}

int
init_module(module_phase_t phase)
{
	switch (phase) {
	case MODULE_PHASE_INIT: {
		source_t source = {
			.name = "acpitemp",
			.write = acpitemp_write,
		};
		acpitemp_sh = register_source(&source);
		return (acpitemp_sh == NULL);
	}
	case MODULE_PHASE_EXIT:
		return forget_source(acpitemp_sh);
	}
	return 0;
}
